export default class Utils {
    static getMinMaxForMonth(data: { x: any, y: any }[], keyValue: 'x' | 'y', keyDate: 'x' | 'y', grouped?: boolean) {
        const monthMap: { [key: string]: { min: { x: any, y: any }, max: { x: any, y: any } }} = {};

        for (let item of data) {
            const monthIndex = this.getYearAndMonthUTC(item[keyDate] as Date);

            if (!monthMap[monthIndex]) {
                monthMap[monthIndex] = { min: item, max: item };
            } else {
                if (monthMap[monthIndex].min[keyValue] > item[keyValue]) monthMap[monthIndex].min = item;
                else if (monthMap[monthIndex].max[keyValue] < item[keyValue]) monthMap[monthIndex].max = item;
            }
        }

        if (grouped) return monthMap;

        const min = Object.values(monthMap).map(item => item.min);
        const max = Object.values(monthMap).map(item => item.max);

        return { max, min };
    }

    static getYearAndMonthUTC(date: Date) {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;

        return `${year}-${this.formatDate(month)}`;
    }

    static formatDate(number: number) {
        return number < 10 ? '0' + number : number
    }

    static getMaxPointByDate(data: { x: any, y: any }[], keyDate: 'x' | 'y') {
        let maxPoint = data[0];

        for (let i = 1; i < data.length; i++) {
            if ((maxPoint[keyDate] as Date).getTime() < (data[i][keyDate] as Date).getTime()) {
                maxPoint = data[i];
            }
        }

        return maxPoint;
    }

    static toRound(number: number, exponent: number) {
        const n = Math.pow(10, exponent);
        return (Math.round(number * n) / n).toFixed(exponent);
    }
}